package top.as.sean.api.controller.common;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.as.sean.common.response.Result;
import top.as.sean.common.rsa.RsaUtils;

import java.util.HashMap;

/**
 * 秘钥
 *
 * @author: ArchieSean
 * @create: 2023/1/30
 */
@RestController
@RequestMapping("rsa")
@RequiredArgsConstructor
public class RsaController {

    private final RsaUtils rsaUtils;

    @PostMapping("valid")
    public Result<String> valid(@RequestBody HashMap<String, String> map) {
        rsaUtils.checkLegal(map.get("text"));

        String text = rsaUtils.decode(map.get("text"));
        return Result.success(text);
    }

    /**
     * 获取公钥
     *
     * @return str 公钥
     */
    @GetMapping("pub")
    public Result<String> getPublicKey() {
        String publicKey = StrUtil.str(Base64.encodeBase64(rsaUtils.getRsa().getPublicKey().getEncoded()),
                CharsetUtil.CHARSET_UTF_8);
        return Result.success(publicKey);
    }
}
